from django.conf import settings
from fb.utils import oauth
import httplib
import urllib
try:
  import json as simplejson
except ImportError:
  from django.utils import simplejson  # Python 2.5 fallback

SUBSCRIPTION_PATH = 'https://graph.facebook.com/%s/subscriptions' % settings.FACEBOOK_APP_ID

def fetch_subscriptions(access_token=None):
  if not access_token:
    access_token = oauth.fetch_app_access_token()
    
  params = {
    'access_token': access_token
  }
  uri = '%s?%s' % (SUBSCRIPTION_PATH, urllib.urlencode(params))
  response = urllib.urlopen(uri)
  data = simplejson.loads(response.read())
  return data["data"]

def update_subscription(object, fields):
  callback_url = '%s%s' % (
    settings.HOST_URL_PREFIX, 
    urlresolvers.reverse('subscription_update_handler')
  ) 
  params = {
    'object': object,
    'fields': ','.join(fields),
    'callback_url': callback_uri,
    'verify_token': '%s|%s' % (object, ','.join(fields)) 
  }
  headers = {
    "Content-type": "application/x-www-form-urlencoded",
    "Accept": "text/plain"
  }
  conn = httplib.HTTPConnection(SUBSCRIPTION_PATH)
  conn.request("POST", "", urllib.urlencode(params), headers)
  
def delete_subscription(object):
  params = {'object': object}
  conn = httplib.HTTPConnection(SUBSCRIPTION_PATH)
  conn.request("DELETE", "", urllib.urlencode(params))
  
  
  
    
  